<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <div>
        <el-button v-if="canAddUser" type="info" @click="exportUsers" :loading="exporting">
          <i class="el-icon-download"></i> 导出Excel
        </el-button>
        <el-button v-if="canAddUser" type="success" @click="showImportDialog">Excel导入</el-button>
        <el-button v-if="canAddUser" type="primary" @click="handleAdd">添加用户</el-button>
      </div>
    </div>

    <el-dialog title="Excel批量导入用户" :visible.sync="importDialogVisible" width="500px">
      <div class="import-content">
        <div class="template-section">
          <h4>1. 下载模板</h4>
          <p>请先下载Excel模板，按照模板格式填写用户信息</p>
          <el-button type="primary" @click="downloadTemplate" :loading="templateDownloading">
            <i class="el-icon-download"></i> 下载Excel模板
          </el-button>
        </div>

        <el-divider></el-divider>

        <div class="upload-section">
          <h4>2. 上传文件</h4>
          <el-upload
              ref="upload"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :auto-upload="false"
              accept=".xlsx,.xls"
              :limit="1">
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="uploading">上传导入</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过10MB</div>
          </el-upload>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- User Table -->
    <el-table :data="users" border style="width: 100%" v-loading="loading">
      <!-- 表格列保持不变 -->
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="age" label="年龄" width="70" />
      <el-table-column prop="gender" label="性别" width="70" />
      <el-table-column prop="role" label="角色" width="100">
        <template slot-scope="scope">
          <el-tag :type="getRoleTag(scope.row.role)">{{ getRoleText(scope.row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag
              :type="getStatusTag(scope.row.status)"
              :class="{ 'clickable-status': canChangeStatus(scope.row) }"
              @click="handleStatusClick(scope.row)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button v-if="canEditUser" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="canDeleteUser" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option
                v-for="role in availableRoles"
                :key="role.value"
                :label="role.label"
                :value="role.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>

    <!-- Status Dialog -->
    <el-dialog title="修改用户状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="statusForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="激活" value="ACTIVE"></el-option>
            <el-option label="禁用" value="INACTIVE"></el-option>
            <el-option label="锁定" value="LOCKED"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserStatus" :loading="statusUpdating">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserManagement',
  data() {
    return {
      // 添加导入相关数据
      importDialogVisible: false,
      exporting: false,
      templateDownloading: false,
      uploading: false,
      uploadUrl: '/api/users/import',
      uploadHeaders: {
        'X-Username': localStorage.getItem('username') || 'system'
      },
      users: [],
      loading: false,
      submitting: false,
      dialogVisible: false,
      isEdit: false,
      dialogTitle: '添加用户',
      currentUserRole: localStorage.getItem('userRole') || 'USER',
      currentUserId: localStorage.getItem('userId'),
      statusDialogVisible: false,
      statusUpdating: false,
      statusForm: {
        userId: null,
        username: '',
        currentStatus: '',
        newStatus: ''
      },
      form: {
        id: null,
        username: '',
        password: '',
        name: '',
        email: '',
        phone: '',
        age: null,
        gender: '',
        address: '',
        role: 'USER'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 是否可以添加用户
    canAddUser() {
      return this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN'
    },
    // 是否可以编辑用户
    canEditUser() {
      return this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN'
    },
    // 是否可以删除用户
    canDeleteUser() {
      return this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN'
    },
    // 可选择的角色
    availableRoles() {
      if (this.currentUserRole === 'SUPER_ADMIN') {
        return [
          { label: '超级管理员', value: 'SUPER_ADMIN' },
          { label: '管理员', value: 'ADMIN' },
          { label: '普通用户', value: 'USER' }
        ]
      } else if (this.currentUserRole === 'ADMIN') {
        return [
          { label: '普通用户', value: 'USER' }
        ]
      }
      return []
    }
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    // 导出用户数据
    exportUsers() {
      this.exporting = true

      const operatedBy = localStorage.getItem('username') || 'system'
      this.$axios.get('/api/users/export', {
        responseType: 'blob',
        headers: {
          'X-Username': operatedBy
        }
      })
          .then(response => {
            // 创建下载链接
            const blob = new Blob([response.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url

            // 生成文件名（包含当前时间）
            const now = new Date()
            const timestamp = now.getFullYear() +
                String(now.getMonth() + 1).padStart(2, '0') +
                String(now.getDate()).padStart(2, '0') + '_' +
                String(now.getHours()).padStart(2, '0') +
                String(now.getMinutes()).padStart(2, '0')

            link.download = `用户数据导出_${timestamp}.xlsx`
            link.click()
            window.URL.revokeObjectURL(url)

            this.$message.success('用户数据导出成功')
          })
          .catch(error => {
            console.error('导出失败:', error)
            if (error.response && error.response.status === 403) {
              this.$message.error('权限不足，无法导出用户数据')
            } else {
              this.$message.error('导出失败，请稍后重试')
            }
          })
          .finally(() => {
            this.exporting = false
          })
    },
    // 显示导入弹窗
    showImportDialog() {
      this.importDialogVisible = true
    },

    // 下载Excel模板
    downloadTemplate() {
      this.templateDownloading = true
      this.$axios.get('/api/users/template', {
        responseType: 'blob',
        headers: {
          'X-Username': localStorage.getItem('username') || 'system'
        }
      })
          .then(response => {
            const blob = new Blob([response.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = '用户导入模板.xlsx'
            link.click()
            window.URL.revokeObjectURL(url)
            this.$message.success('模板下载成功')
          })
          .catch(error => {
            console.error('下载模板失败:', error)
            this.$message.error('下载模板失败')
          })
          .finally(() => {
            this.templateDownloading = false
          })
    },

    // 上传前检查
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
        return false
      }
      return true
    },

    // 提交上传
    submitUpload() {
      this.uploading = true
      this.$refs.upload.submit()
    },

    // 上传成功
    handleUploadSuccess(response) {
      this.uploading = false
      this.$message.success(`导入成功！成功导入${response.successCount}个用户，失败${response.failCount}个`)
      this.importDialogVisible = false
      this.fetchUsers() // 刷新用户列表
      this.$refs.upload.clearFiles()
    },

    // 上传失败
    handleUploadError(error) {
      this.uploading = false
      console.error('上传失败:', error)
      this.$message.error('文件上传失败，请检查文件格式')
    },

    // 获取角色标签样式
    getRoleTag(role) {
      switch(role) {
        case 'SUPER_ADMIN': return 'danger'
        case 'ADMIN': return 'warning'
        case 'USER': return 'info'
        default: return 'info'
      }
    },
    // 获取角色文本
    getRoleText(role) {
      switch(role) {
        case 'SUPER_ADMIN': return '超级管理员'
        case 'ADMIN': return '管理员'
        case 'USER': return '普通用户'
        default: return '未知'
      }
    },
    // 获取状态标签样式
    getStatusTag(status) {
      switch(status) {
        case 'ACTIVE': return 'success'
        case 'INACTIVE': return 'warning'
        case 'LOCKED': return 'danger'
        default: return 'info'
      }
    },
    // 获取状态文本
    getStatusText(status) {
      switch(status) {
        case 'ACTIVE': return '激活'
        case 'INACTIVE': return '禁用'
        case 'LOCKED': return '锁定'
        default: return '未知'
      }
    },
    // 是否可以修改状态
    canChangeStatus(user) {
      // 管理员和超级管理员可以修改状态，但不能修改自己的状态
      return (this.currentUserRole === 'SUPER_ADMIN' || this.currentUserRole === 'ADMIN') &&
          user.id != this.currentUserId
    },
    // 处理状态点击
    handleStatusClick(user) {
      if (this.canChangeStatus(user)) {
        this.statusForm = {
          userId: user.id,
          username: user.username,
          currentStatus: user.status,
          newStatus: user.status
        }
        this.statusDialogVisible = true
      }
    },
    // 更新用户状态
    updateUserStatus() {
      if (this.statusForm.currentStatus === this.statusForm.newStatus) {
        this.$message.warning('状态未发生变化')
        return
      }

      this.statusUpdating = true
      const operatedBy = localStorage.getItem('username') || 'system'
      const config = {
        headers: { 'X-Username': operatedBy }
      }

      this.$axios.put(`/api/users/${this.statusForm.userId}/status`, {
        status: this.statusForm.newStatus
      }, config)
          .then(() => {
            this.$message.success('状态更新成功')
            this.statusDialogVisible = false
            this.fetchUsers()
          })
          .catch(error => {
            console.error('Error updating status:', error)
            this.$message.error('状态更新失败')
          })
          .finally(() => {
            this.statusUpdating = false
          })
    },

    fetchUsers() {
      this.loading = true;

      const operatedBy = localStorage.getItem('username') || 'system';
            this.$axios.get('/api/users', {
                    headers: {
                      'X-Username': operatedBy
                    }
            })
          .then(response => {
            this.users = response.data;
          })
          .catch(error => {
            console.error('Error fetching users:', error);
            this.$message.error('获取用户列表失败');
          })
          .finally(() => {
            this.loading = false;
          });
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = '添加用户';
      this.submitting = false;
      this.form = {
        id: null,
        username: '',
        password: '',
        name: '',
        email: '',
        phone: '',
        age: null,
        gender: '',
        address: '',
        role: 'USER'
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.userForm) {
          this.$refs.userForm.clearValidate();
        }
      });
    },

    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑用户';
      this.submitting = false;
      this.form = {...row};
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.userForm) {
          this.$refs.userForm.clearValidate();
        }
      });
    },

    handleDelete(row) {
      this.$confirm('确认删除此用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const operatedBy = localStorage.getItem('username') || 'system';
        const config = {
          headers: { 'X-Username': operatedBy }
        };

        this.$axios.delete(`/api/users/${row.id}`, config)
            .then(() => {
              this.$message.success('删除成功');
              this.fetchUsers();
            })
            .catch(error => {
              console.error('Error deleting user:', error);
              this.$message.error('删除用户失败');
            });
      }).catch(() => {});
    },

    submitForm() {
      if (this.submitting) return;

      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.submitting = true;

          const operatedBy = localStorage.getItem('username') || 'system';
          const config = {
            headers: { 'X-Username': operatedBy },
            timeout: 30000
          };

          let requestPromise;

          if (this.isEdit) {
            requestPromise = this.$axios.put(`/api/users/${this.form.id}`, this.form, config);
          } else {
            const userWithoutId = { ...this.form };
            delete userWithoutId.id;
            requestPromise = this.$axios.post('/api/users', userWithoutId, config);
          }

          const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error('请求超时，请稍后重试')), 30000);
          });

          Promise.race([requestPromise, timeoutPromise])
              .then(response => {
                if (this.isEdit) {
                  this.$message.success('更新成功');
                } else {
                  this.$message.success('添加成功');
                }
                this.dialogVisible = false;
                this.fetchUsers();
              })
              .catch(error => {
                if (error.message === '请求超时，请稍后重试') {
                  this.$message.error(error.message);
                } else if (error.response) {
                  if (error.response.status === 409) {
                    this.$message.error('用户名已存在，请更换用户名');
                  } else {
                    this.$message.error(`操作失败: ${error.response.data?.message || error.message || '服务器错误'}`);
                  }
                } else if (error.request) {
                  this.$message.error('服务器无响应，请检查网络连接或联系管理员');
                } else {
                  this.$message.error(`请求错误: ${error.message}`);
                }
              })
              .finally(() => {
                this.submitting = false;
              });
        }
      });
    }
  }
}
</script>
<style scoped>
.import-content {
  padding: 20px 0;
}

.template-section, .upload-section {
  margin-bottom: 20px;
}

.template-section h4, .upload-section h4 {
  margin-bottom: 10px;
  color: #303133;
}

.template-section p {
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header div {
  display: flex;
  gap: 10px;
}
</style>